package lo53.bardoux.positionning;

import lo53.bardoux.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class MapView extends SurfaceView implements SurfaceHolder.Callback{

	private Bitmap map;
	private float pointX = -1;
	private float pointY = -1;
	
	private SurfaceHolder holder;
	private CanvasThread canvasThread;
	private Locate locate;
	
	public MapView(Locate locate) {
		super(locate);
		this.locate = locate;
		this.map = (Bitmap) BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.map);
		this.holder = getHolder();
		// Sets itself as the callback for the holder
		this.holder.addCallback(this);
		this.canvasThread = new CanvasThread();
	}

	public void setPointX(float pointX) {
		this.pointX = pointX;
	}

	public void setPointY(float pointY) {
		this.pointY = pointY;
	}

	@Override
	public void onDraw(Canvas canvas) {
		canvas.drawBitmap(this.map, 0, 0, null);
		if(this.pointX != -1 && this.pointY != -1){
			Paint paint = new Paint();
			paint.setColor(Color.RED);
			canvas.drawCircle(this.pointX, this.pointY, 10, paint);
		}
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		
	}

	public void surfaceCreated(SurfaceHolder holder) {
		this.canvasThread.start();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
        this.canvasThread.run = false;
        while (retry) {
            try {
            	this.canvasThread.join();
                retry = false;
            } catch (InterruptedException e) {}
        }
	}
	
	public class CanvasThread extends Thread {
		// To stop the loop
		public boolean run = true;
	    @Override
	    public void run() {
	        Canvas c;
	        while (run) {
	            c = null;
	            try {
	                c = holder.lockCanvas(null);
	                synchronized (holder) {
	                	// To check if run went false while synchronized was blocked
	                    if(run)
	                    	onDraw(c);
	                }
	            } finally {
	                if (c != null) {
	                    holder.unlockCanvasAndPost(c);
	                }
	            }
	        }
	    }
	}
}
